﻿using System.Collections.Generic;
using UnityEngine;

public class CarMeshCompiler
{
    private List<Mesh> mMeshList = new List<Mesh>();

    private float[] mVertexBuffer;
    private int mVertexCount;
    private int[] mTriangleBuffer;
    private int mTriangleCount;

    public float[] VertexBuffer
    {
        get
        {
            return mVertexBuffer;
        }
    }

    public int VertexCount
    {
        get
        {
            return mVertexCount;
        }
    }

    public int[] TriangleBuffer
    {
        get
        {
            return mTriangleBuffer;
        }
    }

    public int TriangleCount
    {
        get
        {
            return mTriangleCount;
        }
    }

    public void AddMesh(Mesh mesh)
    {
        if (!mMeshList.Contains(mesh))
        {
            mMeshList.Add(mesh);
        }
    }

    public void RemoveMesh(Mesh mesh)
    {
        if (mMeshList.Contains(mesh))
        {
            mMeshList.Remove(mesh);
        }
    }

    public void ClearMesh()
    {
        mMeshList.Clear();
    }

    public void Compile()
    {
        mVertexCount = CalculateVertexCount();
        mTriangleCount = CalculateTriangleCount();

        mVertexBuffer = new float[mVertexCount * 3];
        mTriangleBuffer = new int[mTriangleCount * 3];

        int meshCount = mMeshList.Count;
        for (int i = 0; i < meshCount; ++i)
        {

        }
    }

    public int CalculateVertexCount()
    {
        int vertexCount = 0;
        int meshCount = mMeshList.Count;
        for (int i = 0; i < meshCount; ++i)
        {
            if (mMeshList[i] != null)
            {
                vertexCount += mMeshList[i].vertexCount;
            }
        }

        return vertexCount;
    }

    public int CalculateTriangleCount()
    {
        int triangleCount = 0;
        int meshCount = mMeshList.Count;
        for (int i = 0; i < meshCount; ++i)
        {
            if (mMeshList[i] != null)
            {
                if (mMeshList[i].triangles != null)
                {
                    triangleCount += mMeshList[i].triangles.Length / 3;
                }
            }
        }

        return triangleCount;
    }

    private void WriteVertexBuffer()
    {

    }
}
